/*
 * syn6288.c
 *
 *  Created on: 2015-03-12
 *      Author: atreyu
 */

#include "syn6288.h"

uint8_t BackGroundMusic = 0x08;
uint8_t TextCodec = 0x00;
uint8_t FrameHeader[5] = { 0xfd, 0x00, 0x00, 0x00, 0x00 };

void initSYN(void)
{
	bt_UARTsend("Init TTS");
	SYN_SetBackGroundMusic(SYNBackGroundMusic0);
	SYN_SetTextCodec(SYNTextCodecGBK);

	//to test run these after init

	//if(speak_on) SYN_Say((unsigned char *)Volume"ringo");

	loading_bar(27);
	load_okfail(1);
}

uint8_t CheckXOR(const uint8_t * Object, uint8_t Length)
{
	uint8_t Result = 0;
	uint8_t i;

	Result ^= FrameHeader[0];
	Result ^= FrameHeader[1];
	Result ^= FrameHeader[2];
	Result ^= FrameHeader[3];
	Result ^= FrameHeader[4];
	for(i = 0; i < Length; i++)
	{
		Result ^= Object[i];
	}

	return Result;
}

void SYN_SetBackGroundMusic(uint8_t Code)
{
	BackGroundMusic = Code;
}

void SYN_SetTextCodec(uint8_t Code)
{
	TextCodec = Code;
}

void SYN_SentHeader(uint16_t DataAreaLength)
{
	FrameHeader[1] = (DataAreaLength & 0xff00) >> 8;
	FrameHeader[2] = (DataAreaLength & 0xff);
	tts_UARTputc(FrameHeader[0]);
	tts_UARTputc(FrameHeader[1]);
	tts_UARTputc(FrameHeader[2]);
	tts_UARTputc(FrameHeader[3]);
	tts_UARTputc(FrameHeader[4]);
}

void SYN_SetBaudRate(uint8_t BaudRate)
{
	// first tell the SYN6288 to change the expected baudrate
	FrameHeader[3] = 0x31;
	FrameHeader[4] = BaudRate;
	SYN_SentHeader(3);
	tts_UARTputc(FrameHeader[3]);
	tts_UARTputc(FrameHeader[4]);

	tts_UARTputc(CheckXOR(FrameHeader, 0));
}

void SYN_Say(const uint8_t * Text) // maximum 20 chars
{
	uint16_t i;
	uint16_t Length;

	for(Length = 0;;Length++){
		if(Text[Length] == '\0')
		break;
	}

	FrameHeader[3] = 0x01;
	FrameHeader[4] = BackGroundMusic | TextCodec;
	SYN_SentHeader(Length + 3);
	for(i = 0;i < Length;i++){
		tts_UARTputc(Text[i]);
	}
	tts_UARTputc(CheckXOR(Text,Length));

	// wait for processing, otherwise the SYN_BUSY won't turn on immediately and
	// the delay below is useless.
	//ROM_SysCtlDelay(200000);

	// wait until speaking is completed before exiting the function.
	//while (SYN_BUSY);

	// wait a bit more before exiting, otherwise the chip is still busy
	// and may ignore the next command set
	//ROM_SysCtlDelay(200000);
}

void SYN_SpeakingPaused(void)
{
	FrameHeader[3] = 0x03;
	FrameHeader[4] = 0x00;
	SYN_SentHeader(1);
	tts_UARTputc(FrameHeader[3]);
	tts_UARTputc(CheckXOR(FrameHeader,0));
}

void SYN_SpeakingResume(void)
{
	FrameHeader[3] = 0x04;
	FrameHeader[4] = 0x00;
	SYN_SentHeader(1);
	tts_UARTputc(FrameHeader[3]);
	tts_UARTputc(CheckXOR(FrameHeader,0));
}

void SYN_SpeakingStop(void)
{
	FrameHeader[3] = 0x02;
	FrameHeader[4] = 0x00;
	SYN_SentHeader(1);
	tts_UARTputc(FrameHeader[3]);
	tts_UARTputc(CheckXOR(FrameHeader,0));
}
